package com.zrc.superframe_net.common.download

import com.zrc.superframe_net.room.download.DownloadInfo
import com.zrc.superframe_net.room.download.DownloadState
import com.zrc.superframe_net.common.net.Net
import io.reactivex.Observer
import io.reactivex.disposables.Disposable

/**
 * @Author: superman
 * @CreateTime: 6/27/21
 * @Describe:下载监听回调
 */
class NetDownloadObserver<T>(
    private val downInfo: DownloadInfo,//当前绑定的下载地址 -> 因为不可能 有同一URL 在下载. 都被我用来当ID
    private val callBack: NetDownloadCallBack? = null //回调
) : Observer<T> {

    private var mDisposable: Disposable? = null//用于关闭上下流

    override fun onSubscribe(d: Disposable) {
        Net.log("NetDownloadObserver -> onSubscribe")
        mDisposable = d
        callBack?.updateState(downInfo, DownloadState.DOWN)
    }

    override fun onNext(value: T) {
        Net.log("NetDownloadObserver -> onNext")
    }

    override fun onError(e: Throwable) {
        Net.log("updateDownloadState -> onError")
        callBack?.updateState(downInfo, DownloadState.ERROR)
    }

    override fun onComplete() {
        Net.log("onComplete -> onComplete")
        callBack?.updateState(downInfo, DownloadState.FINISH)
    }

    fun dispose() {// 关闭
        mDisposable?.let {
            if (!it.isDisposed) {
                it.dispose()
            }
        }
    }
}